package com.yiren.dbaa.module.exam.view.id;

import android.app.Activity;
import android.os.Handler;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.TextureMapView;
import com.yiren.backstage.config.api.LoadConfigApi;
import com.yiren.backstage.config.bean.device.UserParamConfigBean;
import com.yiren.backstage.currency.bean.CarStateBean;
import com.yiren.backstage.currency.bean.GpsInfoBean;
import com.yiren.backstage.currency.entity.LineInfoEntity;
import com.yiren.backstage.currency.bean.LinePointBean;
import com.yiren.backstage.currency.entity.ProjectEntity;
import com.yiren.backstage.currency.enums.CarStateValueEnum;
import com.yiren.backstage.currency.enums.ProjectTypeEnum;
import com.yiren.backstage.currency.enums.TaskStateEnum;
import com.yiren.backstage.currency.utils.GpsUtil;
import com.yiren.backstage.currency.utils.StringUtil;
import com.yiren.dbaa.R;
import com.yiren.dbaa.module.exam.api.IExamViewApi;
import com.yiren.dbaa.util.MeterTransferUtil;
import com.yiren.dbaa.view.MapRelativeLayout;
import com.yiren.dbaa.view.TrajectoryMapView;

import org.apache.commons.lang.StringUtils;

/**
 * Created by WANGRONGXIANG
 * on 2022/4/26
 * Describe 考试页面通用地图信息id
 */
public class ExamMapId {

    private Activity mActivity;
    private IExamViewApi iExamViewApi;     //考试数据处理类
    private UserParamConfigBean userParamConfig;

    private LinearLayout llExamMain;
    private MapRelativeLayout rlMapView;
    private RelativeLayout rlGjdMap;
    private FrameLayout flMapView;
    private RelativeLayout rlCoverInfo;  //高精度轨迹当前项目下一项目
    private TextView tvCurProG;          //高精度当前项目
    private TextView tvNextProG;         //高精度下一个项目
    private LinearLayout llCoverInfo;    //低精度百度地图当前项目下一项目
    private TextView tvCurProD;          //低精度当前项目
    private TextView tvNextProD;         //低精度下一个项目
    private LinearLayout llLeftInfo;     //高精度左边信息
    private TextView tvLeftDis;          //左边距
    private TextView tvRightDis;         //右边距
    private LinearLayout llDeflexDis;    //高精度偏转距离
    private TextView tvDeflexLeft;       //左偏转
    private TextView tvDeflexRight;      //右偏转
    private LinearLayout llProDetail;    //右边项目信息
    private TextView tvInfo1;            //信息1
    private TextView tvInfo2;            //信息2
    private TextView tvInfo3;            //信息3
    private TextView tvInfo4;            //信息4
    private ImageView ivCloseTraject;    //关闭轨迹框
    private ImageView ivScaleTraject;    //缩放轨迹框
    private ImageView ivAddAccuracy;     //关闭轨迹框
    private ImageView ivReduceAccuracy;  //关闭轨迹框

    /*** 当前操作线路 */
    protected LineInfoEntity lineInfo;
    /*** 当前正在执行的项目 */
    private ProjectEntity curExecuteProject;
    /*** 下一个将要执行的线路点位 */
    private LinePointBean nextLinePoint;
    /*** 项目开始里程（毫米） */
    private float projectStartMileage;
    /*** 是否高精度显示 */
    private boolean isGjdShow;
    /*** 高精度模式下卫星数是否小于3 */
    private boolean isSmall3Satellite;
    /*** 是否是点击轨迹预览显示轨迹弹框 */
    private boolean isClickPreview;
    /*** 直线行驶轨迹框是否自动显示过 */
    private boolean isShowZxxs;
    /*** 靠边停车轨迹框是否自动显示过 */
    private boolean isShowKbtc;
    /*** 会车轨迹框是否自动显示过 */
    private boolean isShowHc;
    /*** 是否踩过刹车 */
    private boolean isBrakeing;
    /*** 播报后多少米开始踩刹车 */
    protected int brakeingMileage = 0;
    /*** 左转灯光开启时间 */
    private long leftLightStartTime = 0;
    /*** 右转灯光开启时间 */
    private long rightLightStartTime = 0;
    /*** 直线行驶偏转距离 */
    private int deflectDistance = 0;
    /*** 直线行驶偏移角度 */
    private double deflectAngle = 0;
    /*** 灯光类型 */
    private int dg = 0;
    /*** 地图或轨迹缩放倍数 0：1个像素 1：中等 2:最大 */
    private int scale = 0;
    /*** 高精度地图 */
    private TrajectoryMapView mapView;
    /*** 百度地图 */
    private TextureMapView tmvMapView;
    private BaiduMap mBaiduMap;

    public ExamMapId(Activity mActivity, IExamViewApi iExamViewApi) {
        this.mActivity = mActivity;
        this.iExamViewApi = iExamViewApi;
        initView();
        initData();
        setListener();
    }

    private void initView() {
        llExamMain = mActivity.findViewById(R.id.ll_exam_main);
        rlMapView = mActivity.findViewById(R.id.rl_map_view);
        rlGjdMap = mActivity.findViewById(R.id.rl_gjd_map);
        flMapView = mActivity.findViewById(R.id.fl_mapView);
        rlCoverInfo = mActivity.findViewById(R.id.rl_cover_info);
        tvCurProG = mActivity.findViewById(R.id.tv_cur_pro_g);
        tvNextProG = mActivity.findViewById(R.id.tv_next_pro_g);
        llCoverInfo = mActivity.findViewById(R.id.ll_cover_info);
        tvCurProD = mActivity.findViewById(R.id.tv_cur_pro_d);
        tvNextProD = mActivity.findViewById(R.id.tv_next_pro_d);
        llLeftInfo = mActivity.findViewById(R.id.ll_left_info);
        tvLeftDis = mActivity.findViewById(R.id.tv_left_dis);
        tvRightDis = mActivity.findViewById(R.id.tv_right_dis);
        llDeflexDis = mActivity.findViewById(R.id.ll_deflex_dis);
        tvDeflexLeft = mActivity.findViewById(R.id.tv_deflex_left);
        tvDeflexRight = mActivity.findViewById(R.id.tv_deflex_right);
        llProDetail = mActivity.findViewById(R.id.ll_pro_detail);
        tvInfo1 = mActivity.findViewById(R.id.tv_info_1);
        tvInfo2 = mActivity.findViewById(R.id.tv_info_2);
        tvInfo3 = mActivity.findViewById(R.id.tv_info_3);
        tvInfo4 = mActivity.findViewById(R.id.tv_info_4);
        ivCloseTraject = mActivity.findViewById(R.id.iv_close_traject);
        ivScaleTraject = mActivity.findViewById(R.id.iv_scale_traject);
        ivAddAccuracy = mActivity.findViewById(R.id.iv_add_accuracy);
        ivReduceAccuracy = mActivity.findViewById(R.id.iv_reduce_accuracy);
    }

    private void initData() {
        userParamConfig = LoadConfigApi.loadUserParamConfig(mActivity);
        isGjdShow = userParamConfig.isHasGjdInterface();
        isSmall3Satellite = !isGjdShow;
    }

    private void setListener() {
        //点击地图空白地方
        rlMapView.setListener(() -> setMapViewScale(0));
        //关闭轨迹
        ivCloseTraject.setOnClickListener(v -> setMapViewScale(0));
        //缩放轨迹
        ivScaleTraject.setOnClickListener(v -> setMapViewScale(scale == 1 ? 2 : 1));
        //放大比例尺
        ivAddAccuracy.setOnClickListener(v -> {
            if (null != mapView) mapView.setAccuracy(false);
        });
        //缩小比例尺
        ivReduceAccuracy.setOnClickListener(v -> {
            if (null != mapView) mapView.setAccuracy(true);
        });
    }

    /**
     * 点击轨迹预览
     */
    public void clickPreview() {
        rlGjdMap.setVisibility(View.VISIBLE);
        isClickPreview = true;
        setMapViewScale(1);
    }

    /**
     * 设置当前的项目以及项目开始里程
     */
    public void setCurrentProject(ProjectEntity projectEntity, TaskStateEnum taskState) {
        if (taskState == TaskStateEnum.IN_PROCESS) {
            curExecuteProject = projectEntity;
            projectStartMileage = CarStateBean.getInstance().getTotalMileage();
        } else if (taskState == TaskStateEnum.FINISH) {
            if (null != curExecuteProject && curExecuteProject.getId() == projectEntity.getId()) {
                curExecuteProject = null;
            }
        }
    }

    /**
     * 更新灯光、车辆图标、位置状态信息
     */
    public void updateCarStatus(CarStateBean carState, GpsInfoBean gps) {
        iExamViewApi.carStateImageSwitch(llExamMain, carState);
        iExamViewApi.updateLocationInfo(gps, mBaiduMap);
        //设置不同灯光下的车辆图标
        dg = iExamViewApi.setLightCarInfo(mapView, carState);
    }

    /**
     * 设置高精度轨迹或百度地图窗口入口
     */
    public void setMapViewScale(int scale) {
        if (this.scale == scale) return;
        this.scale = scale;
        if (scale == 0) isClickPreview = false;
        if (rlGjdMap.getVisibility() != View.VISIBLE)
            rlGjdMap.setVisibility(View.VISIBLE);
        rlGjdMap.setLayoutParams(iExamViewApi.getMapRelativeParam(scale));
        showTrajectory();
    }

    /**
     * 显示轨迹上面的布局
     */
    private void showTrajectory() {
        if (scale == 1) {
            ivScaleTraject.setImageResource(isGjdShow ? R.mipmap.scale_big : R.mipmap.scale_big_d);
        } else if (scale == 2) {
            ivScaleTraject.setImageResource(isGjdShow ? R.mipmap.scale_small : R.mipmap.scale_small_d);
        }
        ivCloseTraject.setImageResource(isGjdShow ? R.mipmap.close : R.mipmap.close_d);
        ivAddAccuracy.setVisibility(isGjdShow ? View.VISIBLE : View.GONE);
        ivReduceAccuracy.setVisibility(isGjdShow ? View.VISIBLE : View.GONE);
        llLeftInfo.setVisibility(isGjdShow ? View.VISIBLE : View.GONE);
        llCoverInfo.setVisibility(isGjdShow ? View.GONE : View.VISIBLE);
        rlCoverInfo.setVisibility(isGjdShow ? View.VISIBLE : View.GONE);
        if (isGjdShow) { //高精度
            if (mapView == null) examViewResumeEvent();
        } else   //低精度
            if (tmvMapView == null) examViewResumeBaidu();
    }

    /**
     * 重新显示高精度轨迹
     */
    private void examViewResumeEvent() {
        flMapView.removeAllViews();
        mapView = iExamViewApi.getGjdMapView(mapView);
        flMapView.addView(mapView);
        mapView.setOnMapViewClickListener(() -> setMapViewScale(scale == 1 ? 2 : 1));
    }

    /**
     * 重新显示百度地图
     */
    private void examViewResumeBaidu() {
        flMapView.removeAllViews();
        if (mapView != null) mapView.stopCheck();
        tmvMapView = iExamViewApi.getDjdMapView();
        flMapView.addView(tmvMapView);
        mBaiduMap = iExamViewApi.getBaiduMap(mBaiduMap, tmvMapView);
        new Handler().postDelayed(() -> iExamViewApi.drawBaiduMarker(lineInfo, mBaiduMap), 500);
    }

    /**
     * 高低精度掉线上线时的状态切换
     */
    public void setCurrentStatus(GpsInfoBean gps) {
        if (userParamConfig.isHasGjdInterface()) {  //只有打开了高精度开关，才会有高精度掉线与上线的问题
            if (isGjdShow && (gps.getStatusPosition() < 3 || gps.getStatusDirection() < 3)) {
                //高精度掉线变成低精度，隐藏轨迹框
                isGjdShow = false;
                isSmall3Satellite = true;
                if (rlGjdMap.getVisibility() == View.VISIBLE) {
                    flMapView.removeAllViews();
                    rlGjdMap.setVisibility(View.GONE);
                    scale = 0;
                }
                if (mapView != null) {
                    mapView.stopCheck();
                    mapView = null;
                }
            }
            if (isSmall3Satellite && gps.getStatusPosition() == 3 && gps.getStatusDirection() == 3) {
                //低精度时，高精度定位正常
                isGjdShow = true;
                isSmall3Satellite = false;
            }
            if (isGjdShow && null != flMapView) {
                //如果高精度时显示低精度轨迹，则隐藏低精度轨迹，显示高精度
                View childAt = flMapView.getChildAt(0);
                if (childAt instanceof TextureMapView || null == childAt) {
                    if (null != tmvMapView) {
                        tmvMapView.onDestroy();
                        tmvMapView = null;
                        scale = 0;
                    }
                    setMapViewScale(1);
                }
            }
            if (isGjdShow && mapView == null) {
                setMapViewScale(1);
            }
        }
    }

    /**
     * 设置轨迹信息
     */
    public void setTrajectoryInfo(CarStateBean carState, GpsInfoBean gps) {
        String currentText = "", nextText = "";
        if (curExecuteProject != null && StringUtils.isNotEmpty(curExecuteProject.getName())) {
            currentText = curExecuteProject.getName() + "(已行驶" + MeterTransferUtil.parse2Chinese((carState.getTotalMileage() - projectStartMileage) / 1000) + ")";
            if (isGjdShow && curExecuteProject.getName().contains("直线行驶")) {
                if (carState.getPressSLine() != CarStateValueEnum.PASS && carState.getPressXLine() != CarStateValueEnum.PASS && deflectDistance != 0) {
                    //偏转角度和距离显示
                    llDeflexDis.setVisibility(View.VISIBLE);
                    if (deflectDistance > 0) {
                        tvDeflexLeft.setVisibility(View.INVISIBLE);
                        tvDeflexRight.setVisibility(View.VISIBLE);
                        tvDeflexRight.setText("偏转距离：" + deflectDistance + "厘米");
                    } else {
                        tvDeflexLeft.setVisibility(View.VISIBLE);
                        tvDeflexRight.setVisibility(View.INVISIBLE);
                        tvDeflexLeft.setText("偏转距离：" + Math.abs(deflectDistance) + "厘米");
                    }
                } else {
                    llDeflexDis.setVisibility(View.GONE);
                }
            } else {
                deflectDistance = 0;
                llDeflexDis.setVisibility(View.GONE);
            }
            String info1 = "", info2 = "", info3 = "", info4 = "";
            if (curExecuteProject.getProjectType() == ProjectTypeEnum.LIGHT.toString()) {
                if (carState.getPassingLight() == CarStateValueEnum.OPEN) {
                    info1 = "近光灯：" + carState.getPassingLight().getName();
                } else if (carState.getDistanceLight() == CarStateValueEnum.OPEN) {
                    info1 = "远光灯：" + carState.getDistanceLight().getName();
                }
                if (carState.getCautionLight() == CarStateValueEnum.OPEN) {
                    info2 = "警示灯：" + carState.getCautionLight().getName();
                } else if (carState.getLeftLight() == CarStateValueEnum.OPEN) {
                    info2 = "左转灯：" + carState.getLeftLight().getName();
                } else if (carState.getRightLight() == CarStateValueEnum.OPEN) {
                    info2 = "右转灯：" + carState.getRightLight().getName();
                }
                if (carState.getFoglight() == CarStateValueEnum.OPEN) {
                    info3 = "雾灯：" + carState.getFoglight().getName();
                }
            } else if (curExecuteProject.getName().contains("起步")) {
                info1 = "当前档位：" + carState.getGear().getName();
                info2 = "刹车：" + carState.getFootBrake().getName();
                info3 = "离合：" + carState.getSeparationReunion().getName();
                info4 = "手刹：" + carState.getParkingBrake().getName();
            } else if (curExecuteProject.getName().contains("直线行驶")) {
                if (!isShowZxxs) {
                    isShowZxxs = true;
                    mActivity.runOnUiThread(() -> setMapViewScale(1));
                }
                if (!isGjdShow) {
                    info1 = "偏移角度：" + StringUtil.format(deflectAngle, "#.#") + "度";
                }
            } else if (curExecuteProject.getName().contains("加减")) {
                info1 = "当前档位：" + carState.getGear().getName();
                info2 = "当前车速：" + new Double(carState.getSpeed()).intValue() + "码";
                info3 = "离合状态：" + carState.getSeparationReunion().getName();
            } else if (curExecuteProject.getName().contains("变更车道") || curExecuteProject.getName().contains("左转") || curExecuteProject.getName().contains("右转") || curExecuteProject.getName().contains("掉头")) {
                if (carState.getLeftLight() == CarStateValueEnum.OPEN) {
                    if (leftLightStartTime == 0) {
                        leftLightStartTime = System.currentTimeMillis();
                    }
                    info1 = "左转灯：" + carState.getLeftLight().getName();
                    info2 = "维持时间：" + ((System.currentTimeMillis() - leftLightStartTime) / 1000) + "秒";
                } else if (carState.getRightLight() == CarStateValueEnum.OPEN) {
                    if (rightLightStartTime == 0) {
                        rightLightStartTime = System.currentTimeMillis();
                    }
                    info1 = "右转灯：" + carState.getRightLight().getName();
                    info2 = "维持时间：" + ((System.currentTimeMillis() - rightLightStartTime) / 1000) + "秒";
                }
            } else if (curExecuteProject.getName().contains("靠边停车")) {
                if (!isShowKbtc) {
                    isShowKbtc = true;
                    mActivity.runOnUiThread(() -> setMapViewScale(1));
                }
                if (isGjdShow) {
                    info1 = "前车轮：" + (Math.abs(carState.getRightFrontDistance()) > 400 ? "未检测到线" : carState.getRightFrontDistance() + "厘米");
                    info2 = "后车轮：" + (Math.abs(carState.getRightBackDistance()) > 400 ? "未检测到线" : carState.getRightBackDistance() + "厘米");
                }
                if (carState.getLeftLight() == CarStateValueEnum.OPEN) {
                    if (leftLightStartTime == 0) {
                        leftLightStartTime = System.currentTimeMillis();
                    }
                    info3 = "左转灯：" + carState.getLeftLight().getName();
                    info4 = "维持时间：" + ((System.currentTimeMillis() - leftLightStartTime) / 1000) + "秒";
                } else if (carState.getRightLight() == CarStateValueEnum.OPEN) {
                    if (rightLightStartTime == 0) {
                        rightLightStartTime = System.currentTimeMillis();
                    }
                    info3 = "右转灯：" + carState.getRightLight().getName();
                    info4 = "维持时间：" + ((System.currentTimeMillis() - rightLightStartTime) / 1000) + "秒";
                }
            } else if (curExecuteProject.getName().contains("路口直行") || curExecuteProject.getName().contains("人行横道") || curExecuteProject.getName().contains("学校") || curExecuteProject.getName().contains("公共汽车站")) {
                info1 = "刹车：" + carState.getFootBrake().getName();
                if (carState.getFootBrake() == CarStateValueEnum.STEP_ON) {
                    isBrakeing = true;
                    if (brakeingMileage == 0) {
                        brakeingMileage = (int) ((carState.getTotalMileage() - projectStartMileage) / 1000);
                    }
                }
                if (isBrakeing) info2 = "播报后" + brakeingMileage + "M时踩刹车";
                info3 = "车速：" + new Double(carState.getSpeed()).intValue() + "码";
            } else if (curExecuteProject.getName().contains("会车")) {
                if (!isShowHc) {
                    isShowHc = true;
                    mActivity.runOnUiThread(() -> setMapViewScale(1));
                }
                info1 = "右边线距离：" + ((Math.abs(carState.getRightFrontDistance()) > 400) ? "未检测到线" : carState.getRightFrontDistance() + "厘米");
                info2 = "偏移角度：" + StringUtil.format(carState.getNsbsAngleDiff(), "#.#") + "度";
            } else if (curExecuteProject.getName().contains("超车")) {
                if (carState.getLeftLight() == CarStateValueEnum.OPEN) {
                    if (leftLightStartTime == 0) {
                        leftLightStartTime = System.currentTimeMillis();
                    }
                    info1 = "左转灯：" + carState.getLeftLight().getName();
                    info2 = "维持时间：" + ((System.currentTimeMillis() - leftLightStartTime) / 1000) + "秒";
                } else if (carState.getRightLight() == CarStateValueEnum.OPEN) {
                    if (rightLightStartTime == 0) {
                        rightLightStartTime = System.currentTimeMillis();
                    }
                    info1 = "右转灯：" + carState.getRightLight().getName();
                    info2 = "维持时间：" + ((System.currentTimeMillis() - rightLightStartTime) / 1000) + "秒";
                }
            }
            if (StringUtils.isEmpty(info1) && StringUtils.isEmpty(info2) && StringUtils.isEmpty(info3) && StringUtils.isEmpty(info4)) {
                llProDetail.setVisibility(View.GONE);
            } else {
                llProDetail.setVisibility(View.VISIBLE);
                tvInfo1.setVisibility(StringUtils.isEmpty(info1) ? View.GONE : View.VISIBLE);
                tvInfo2.setVisibility(StringUtils.isEmpty(info2) ? View.GONE : View.VISIBLE);
                tvInfo3.setVisibility(StringUtils.isEmpty(info3) ? View.GONE : View.VISIBLE);
                tvInfo4.setVisibility(StringUtils.isEmpty(info4) ? View.GONE : View.VISIBLE);
                tvInfo1.setText(info1);
                tvInfo2.setText(info2);
                tvInfo3.setText(info3);
                tvInfo4.setText(info4);
            }
            if (carState.getLeftLight() == CarStateValueEnum.CLOSE) {
                leftLightStartTime = 0;
            }
            if (carState.getRightLight() == CarStateValueEnum.CLOSE) {
                rightLightStartTime = 0;
            }
        } else {
            currentText = "正常行驶";
            llProDetail.setVisibility(View.GONE);
            isShowZxxs = isShowHc = isShowKbtc = false;
        }
        //如果是低精度并且是自动弹出轨迹预览
        if (!isGjdShow && !isClickPreview && (isShowZxxs || isShowHc || isShowKbtc)) {
            setMapViewScale(0);
        }
        if (nextLinePoint != null && nextLinePoint.getProjectInfo() != null) {
            int distance = (int) GpsUtil.getDistance(nextLinePoint, gps);
            nextText = nextLinePoint.getProjectInfo().getName() + "(" + distance + "米)";
        } else {
            nextText = "无项目";
        }
        tvCurProG.setText(currentText);
        tvCurProD.setText(currentText);
        tvNextProG.setText(nextText);
        tvNextProD.setText(nextText);
        tvLeftDis.setText("左边距：" + (Math.abs(carState.getLeftFrontDistance()) > 400 ? "未检测到线" : carState.getLeftFrontDistance() + "cm"));
        tvRightDis.setText("右边距：" + (Math.abs(carState.getRightFrontDistance()) > 400 ? "未检测到线" : carState.getRightFrontDistance() + "cm"));
    }

    public LinearLayout getLlExamMain() {
        return llExamMain;
    }

    public int getScale() {
        return scale;
    }

    public boolean isGjdShow() {
        return isGjdShow;
    }

    public ProjectEntity getCurExecuteProject() {
        return curExecuteProject;
    }

    public void setLineInfo(LineInfoEntity lineInfo) {
        this.lineInfo = lineInfo;
    }

    public void setNextLinePoint(LinePointBean nextLinePoint) {
        this.nextLinePoint = nextLinePoint;
    }

    public int getDeflectDistance() {
        return deflectDistance;
    }

    public void setDeflectDistance(int deflectDistance) {
        this.deflectDistance = deflectDistance;
    }

    public void setDeflectAngle(double deflectAngle) {
        this.deflectAngle = deflectAngle;
    }

    public int getDg() {
        return dg;
    }
}
